package weaver.interfaces.qz.job;

import com.engine.kq.biz.KQFormatBiz;
import com.engine.kq.biz.KQWorkTime;
import com.engine.kq.entity.TimeScopeEntity;
import com.engine.kq.entity.WorkTimeEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @version 1.0
 * @Title ecology-9
 * @Company 泛微软件
 * @CreateDate 2025/3/17
 * @Description 新入职员工补卡
 * @Author AdminZm
 */
public class NewEntryInsertCardJob extends BaseCronJob {

    BaseBean baseBean = new BaseBean();

    @Override
    public void execute() {
        baseBean.writeLog("NewEntryInsertCardJob start.");
        try {
            LocalDate currentDate = LocalDate.now();
            RecordSet rs = new RecordSet();
            // 入职自然日天数
            String entryDays = "15";
            // 补卡工作日天数
            String insertCardDays = rs.getPropValue("qz_zm_prop", "insert_card_days");
            if (StringUtils.isEmpty(insertCardDays)) {
                insertCardDays = "3";
            }

            // 获取休息班班次
            List<String> xxShiftList = new ArrayList<>();
            rs.executeQuery("select bc from uf_kqxxbcb ");
            while (rs.next()) {
                String bc = Util.null2String(rs.getString("bc"));
                if (StringUtils.isNotBlank(bc)) {
                    xxShiftList.add(bc);
                }
            }

            KQWorkTime kqWorkTime = new KQWorkTime();
            LocalDate entryDateParam = currentDate.minusDays(Integer.parseInt(entryDays));

            String sign = "auto-add";
            Set<String> cardSet = new HashSet<>();
            rs.execute("select userid, signdate, signtime from hrmschedulesign where signDate >= '" + entryDateParam + "' and signfrom = '" + sign + "'");
            while (rs.next()) {
                String userid = rs.getString("userid");
                String signdate = rs.getString("signdate");
                String signtime = rs.getString("signtime");
                if (StringUtils.isEmpty(userid) || StringUtils.isEmpty(signdate) || StringUtils.isEmpty(signtime)) {
                    continue;
                }
                if (signtime.length() == 5) {
                    signtime = signtime + ":00";
                }
                cardSet.add(userid + "_" + signdate + "_" + signtime);
            }

            // 获取离职日期
            Map<String, String> lzMap = new HashMap<>();
            rs.execute("select resourceid, changedate from HRMSTATUSHISTORY  where type_n = 5");
            while (rs.next()) {
                String resourceid = rs.getString("resourceid");
                String changedate = rs.getString("changedate");
                if (StringUtils.isEmpty(resourceid) || StringUtils.isEmpty(changedate)) {
                    continue;
                }
                lzMap.put(resourceid, changedate);
            }
            List<List> insertParams = new ArrayList<>();

            Map<String, Set<String>> gshSetMap = new HashMap<>();

            rs.execute("SELECT id, companystartdate FROM hrmresource WHERE companystartdate >= '" + entryDateParam + "'");
            while (rs.next()) {
                String id = rs.getString("id");
                String companystartdate = rs.getString("companystartdate");
                if (StringUtils.isEmpty(id) || StringUtils.isEmpty(companystartdate)) {
                    continue;
                }
                String lzrq = lzMap.get(id);
                LocalDate companystartdateLd = LocalDate.parse(companystartdate);
                Set<String> gshSet = new HashSet<>();
                int index = 0;
                for (int i = 0; i <= 15; i++) {
                    if (index >= Integer.parseInt(insertCardDays)) {
                        break;
                    }
                    LocalDate dateTemp = companystartdateLd.plusDays(i);
                    if (dateTemp.isAfter(currentDate)) {
                        break;
                    }
                    if (StringUtils.isNotEmpty(lzrq) && (!companystartdateLd.isAfter(LocalDate.parse(lzrq))) && !dateTemp.isBefore(LocalDate.parse(lzrq))) {
                        break;
                    }
                    WorkTimeEntity workTime = kqWorkTime.getWorkTime(id, dateTemp.toString());
                    String bc = workTime.getSerialId();
                    if (StringUtils.isEmpty(bc) || ((!CollectionUtils.isEmpty(xxShiftList)) && xxShiftList.contains(bc))) {
                        continue;
                    }
                    List<TimeScopeEntity> workTime1 = workTime.getWorkTime();
                    String startTime = null;
                    String endTime = null;
                    for (int j = 0; j < workTime1.size(); j++) {
                        TimeScopeEntity timeScopeEntity = workTime1.get(j);
                        if (j == 0) {
                            startTime = timeScopeEntity.getBeginTime();
                        }
                        if (j == (workTime1.size() - 1)) {
                            endTime = timeScopeEntity.getEndTime();
                        }
                    }

                    boolean haveAdd = false;
                    if (StringUtils.isNotEmpty(startTime)) {
                        if (startTime.length() == 5) {
                            startTime = startTime + ":00";
                        }
                        if (CollectionUtils.isEmpty(cardSet) || !cardSet.contains(id + "_" + dateTemp + "_" + startTime)) {
                            List insertParam = new ArrayList<>();
                            insertParam.add(id);
                            insertParam.add("1");
                            insertParam.add("1");
                            insertParam.add(dateTemp.toString());
                            insertParam.add(startTime);
                            insertParam.add("1");
                            insertParam.add(sign);
                            insertParam.add(dateTemp.toString());
                            insertParams.add(insertParam);
                            haveAdd = true;
                        }
                    }
                    if (StringUtils.isNotEmpty(endTime)) {
                        if (endTime.length() == 5) {
                            endTime = endTime + ":00";
                        }
                        if (CollectionUtils.isEmpty(cardSet) || !cardSet.contains(id + "_" + dateTemp + "_" + endTime)) {
                            List insertParam = new ArrayList<>();
                            insertParam.add(id);
                            insertParam.add("1");
                            insertParam.add("2");
                            insertParam.add(dateTemp.toString());
                            insertParam.add(endTime);
                            insertParam.add("1");
                            insertParam.add(sign);
                            insertParam.add(dateTemp.toString());
                            insertParams.add(insertParam);
                            haveAdd = true;
                        }
                    }
                    index = index + 1;
                    if (haveAdd) {
                        gshSet.add(dateTemp.toString());
                    }
                }

                if (!CollectionUtils.isEmpty(gshSet)) {
                    gshSetMap.put(id, gshSet);
                }
            }

            if (!CollectionUtils.isEmpty(insertParams)) {
                baseBean.writeLog("NewEntryInsertCardJob insertParams size:" + insertParams.size());
                String insertSql = "INSERT INTO HrmScheduleSign(userId, userType, signType, signDate, signTime, isInCom, " +
                        "signFrom, belongdate) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                rs.executeBatchSql(insertSql, insertParams);

                // 考勤格式化
                if (!CollectionUtils.isEmpty(gshSetMap)) {
                    for (Map.Entry<String, Set<String>> entry : gshSetMap.entrySet()) {
                        String yg = entry.getKey();
                        Set<String> needFormatSet = entry.getValue();
                        if (!CollectionUtils.isEmpty(needFormatSet)) {
                            for (String key : needFormatSet) {
                                new KQFormatBiz().formatDate(yg, key);
                            }
                        }
                    }
                }
            } else {
                baseBean.writeLog("NewEntryInsertCardJob insertParams is null.");
            }
        } catch (Exception e) {
            baseBean.writeLog("NewEntryInsertCardJob error:" + e);
        }
        baseBean.writeLog("NewEntryInsertCardJob end.");
    }
}
